package com.woniuxy.util;

import com.woniuxy.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.*;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class MinioUtil {
    @Resource
    private MinioConfig minioConfig;
    @Resource
    private MinioClient minioClient;
    //MultipartFile是专门负责浏览器上传文件的接口
    public Map<String,Object> updateFile(MultipartFile file, String bucketName) throws InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, RegionConflictException {
        HashMap<String, Object> map = new HashMap<>();
        //1.判断文件是否为空
        if (file.isEmpty() || file.getSize() == 0){
            map.put("code",500);
            map.put("msg","文件不能为空");
            return map;
        }
        //2.判断桶是否存在
        boolean flag = minioClient.bucketExists(bucketName);
        if (!flag){
            minioClient.makeBucket(bucketName);
        }else {
            System.out.println("已经存在了 test 这个 Bucket");
        }
        //文件上传 1.文件名称 2.文件格式
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件的后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //修改文件名，确保文件名唯一
        //桶名+时间/UUID+suffix
        String filename = bucketName+"_"+
                System.currentTimeMillis()+"/"+
                UUID.randomUUID()+suffix;



        //上传文件
        InputStream inputStream = file.getInputStream();
        PutObjectOptions putObjectOptions
                = new PutObjectOptions(inputStream.available(), -1);
        minioClient.putObject(bucketName,filename
        ,inputStream,putObjectOptions);

        //回显地址
        String url = minioClient.getObjectUrl(bucketName, filename);

        String substring
                = url.substring(url.indexOf("/" + bucketName) + bucketName.length() + 1);

        map.put("code",200);
        map.put("msg","文件上传成功");
        map.put("url",url);
        map.put("imgSrc",substring);
        return map;
    }
}
